/**
 * elancom Corporation copy right 2012 - 2015  
 *   
 * $Header: https://192.168.1.224/svn/elancom/product/elancom-platform/trunk/src/main/java/com/elancom/framework/commons/json/serializer/JSONSerializerContext.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Id: JSONSerializerContext.java 1034 2012-07-02 03:09:12Z lanzhouxue $
 * $Author: lanzhouxue $
 * $Date: 2012-07-02 11:09:12 +0800 (Mon, 02 Jul 2012) $
 * $Revision: 1034 $
 */
package com.elancom.framework.commons.json.serializer;

/**
 * circular references detect
 * 
 * @author elancom
 */
public final class JSONSerializerContext {

	public static final int DEFAULT_TABLE_SIZE = 128;

	private final Entry[] buckets;
	private final int indexMask;

	public JSONSerializerContext() {
		this(DEFAULT_TABLE_SIZE);
	}

	public JSONSerializerContext(int tableSize) {
		indexMask = tableSize - 1;
		buckets = new Entry[tableSize];
	}

	public final boolean put(Object o) {
		final int hash = System.identityHashCode(o);
		final int bucket = hash & indexMask;

		for (Entry entry = buckets[bucket]; entry != null; entry = entry.next) {
			if (o == entry.object) {
				return true;
			}
		}

		final Entry entry = new Entry(o, hash, buckets[bucket]);
		buckets[bucket] = entry;

		return false;
	}

	protected static final class Entry {

		public final int hashCode;
		public final Object object;

		public Entry next;

		public Entry(Object object, int hash, Entry next) {
			this.object = object;
			this.next = next;
			hashCode = hash;
		}

	}
}
